<script>
import { Select } from '@cci/cui'
import { parseTime } from '@/utils/index.js'

export default {
  name: 'SelectWeek',
  components: {
    Select
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    year: {
      type: [Number, String],
      default: 2019
    },
    month: {
      type: [Number, String],
      default: 6
    },
    startDay: {
      type: [Number, String],
      default: 1 // 0 - 6
    },
    format: {
      type: String,
      default: 'yyyy-mm-dd'
    },
    seperator: {
      type: String,
      default: '~'
    },
    placeholder: {
      type: String,
      default: '请选择'
    }
  },
  data() {
    return {
      val: this.value
    }
  },
  computed: {
    nowMonth() {
      return Number(this.month) - 1 // 0 - 11
    },
    nowYear() {
      return Number(this.year)
    }
  },
  watch: {
    val: {
      deep: true,
      handler: function(value) {
        this.$emit('change', value)
      }
    }
  },
  methods: {
    getOptions() {
      let start, end, startTime, endTime
      const options = []
      const dateTime = new Date(Date.parse(`${this.nowYear}-${this.nowMonth + 1}-01`))
      const day = dateTime.getDay() // 周几
      if (day === this.startDay) {
        startTime = dateTime - 0
      } else {
        if (day < this.startDay && this.startDay !== 0) {
          startTime = dateTime - (7 + day - this.startDay) * 24 * 3600 * 1000
        } else {
          startTime = dateTime - (day - this.startDay) * 24 * 3600 * 1000
        }
      }

      endTime = startTime + 6 * 24 * 3600 * 1000

      while (new Date(startTime).getMonth() === this.nowMonth || new Date(endTime).getMonth() === this.nowMonth) {
        start = parseTime(startTime, this.format)
        end = parseTime(endTime, this.format)
        options.push(`${start}${this.seperator}${end}`)
        startTime = endTime + 24 * 3600 * 1000
        endTime = startTime + 6 * 24 * 3600 * 1000
      }

      return options
    }
  },
  render() {
    const options = this.getOptions()
    return (
      <Select
        v-model={this.val}
      >
        {
          this._l(options, item => (
            <c-option
              key={item}
              label={item}
              value={item} />
          ))
        }
      </Select>
    )
  }
}
</script>

